package org.alfalfa.web.filter;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author : Max-Goday
 * @Created : 2016-10-21
 * @E-mail : goday.max@gmail.com
 * @Version : 1.0
 */
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
	@Override
	public void destroy() {
		System.out.println("过滤器销毁");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		req.getSession().setAttribute("base", getBase(req));

		if (req.getSession().getAttribute("userLoginId") != null &&
				StringUtils.isNotBlank((String) req.getSession().getAttribute("userLoginId"))) {
			chain.doFilter(request, response);
			return;
		}

		String uri = req.getRequestURI().toLowerCase();
		if (uri.matches("[\\w\\/-]+\\.(html|css|js|jpg|jpeg|png|gif|jar|ico|htc|swf|json|otf|eot|svg|ttf|woff|woff2|vm)")) {
			chain.doFilter(request, response);
			return;
		}

		if (req.getRequestURL().indexOf("/vm/login") != -1 ||
				req.getRequestURL().indexOf(getBase(req) + "css") != -1 ||
				req.getRequestURL().indexOf(getBase(req) + "js") != -1 ||
				req.getRequestURL().indexOf(getBase(req) + "image") != -1 ||
				req.getRequestURL().indexOf(getBase(req) + "fonts") != -1 ||
				req.getRequestURL().indexOf(getBase(req) + "component") != -1 ||
				req.getRequestURL().indexOf(getBase(req) + "api/login") != -1 ||
				req.getRequestURL().indexOf(getBase(req) + "api/backdoor") != -1) {
			chain.doFilter(request, response);
			return;
		}

		resp.sendRedirect(getBase(req) + "vm/login");
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
//		System.out.println("过滤器初始化");
	}

	private static String getBase(HttpServletRequest request) {
		if (request == null) return "<BASEPATH>";
		String path = request.getContextPath();
		return request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
	}
}
